import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, register, getUserInfo } from '@/api/user'
import request from '@/utils/request'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  const tokenExpireTime = ref(parseInt(localStorage.getItem('tokenExpireTime') || '0'))

  // 计算属性
  const isLoggedIn = computed(() => {
    if (!token.value) return false
    // 检查token是否过期
    if (Date.now() >= tokenExpireTime.value) {
      logout()
      return false
    }
    return true
  })

  const userId = computed(() => userInfo.value?.id)
  const username = computed(() => userInfo.value?.username)

  const isAdmin = computed(() => {
    return userInfo.value.username === 'admin' && userInfo.value.level === 'DIAMOND'
  })

  // 检查token有效性
  const checkTokenValidity = async () => {
    if (!token.value) return false
    if (Date.now() >= tokenExpireTime.value) {
      logout()
      return false
    }
    try {
      // 尝试获取用户信息来验证token
      await loadUserInfo()
      return true
    } catch (error) {
      if (error.response?.status === 401) {
        logout()
        return false
      }
      return true // 其他错误不影响token有效性
    }
  }

  // 刷新token
  const refreshToken = async () => {
    if (!token.value) return false
    try {
      const response = await request.post('/user/refresh-token')
      if (response.code === 200) {
        token.value = response.data.token
        tokenExpireTime.value = Date.now() + response.data.expiresIn * 1000
        localStorage.setItem('token', token.value)
        localStorage.setItem('tokenExpireTime', tokenExpireTime.value.toString())
        return true
      }
      return false
    } catch (error) {
      console.error('刷新token失败:', error)
      return false
    }
  }

  // 登录
  const loginAction = async (loginData) => {
    try {
      const response = await login(loginData)
      if (response.code === 200) {
        // 保存token和过期时间
        const { token: newToken, expiresIn } = response.data
        token.value = newToken
        tokenExpireTime.value = Date.now() + expiresIn * 1000
        localStorage.setItem('token', token.value)
        localStorage.setItem('tokenExpireTime', tokenExpireTime.value.toString())
        
        // 获取用户信息
        await loadUserInfo()
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: error.message || '登录失败' }
    }
  }

  // 注册
  const registerAction = async (registerData) => {
    try {
      const response = await register(registerData)
      if (response.code === 200) {
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      return { success: false, message: error.message || '注册失败' }
    }
  }

  // 获取用户信息
  const loadUserInfo = async () => {
    try {
      const response = await getUserInfo()
      if (response.code === 200) {
        userInfo.value = response.data
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        return true
      }
      return false
    } catch (error) {
      console.error('获取用户信息失败:', error)
      if (error.response?.status === 401) {
        logout()
      }
      return false
    }
  }

  // 确保用户信息已加载
  const ensureUserInfoLoaded = async () => {
    if (!userInfo.value?.id && token.value) {
      return await loadUserInfo()
    }
    return true
  }

  // 更新用户信息
  const updateUserInfo = (newUserInfo) => {
    userInfo.value = { ...userInfo.value, ...newUserInfo }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    tokenExpireTime.value = 0
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('tokenExpireTime')
  }

  // 初始化时加载用户信息
  if (token.value) {
    loadUserInfo()
  }

  return {
    // 状态
    token,
    userInfo,
    tokenExpireTime,
    
    // 计算属性
    isLoggedIn,
    isAdmin,
    userId,
    username,
    
    // 方法
    loginAction,
    registerAction,
    loadUserInfo,
    updateUserInfo,
    logout,
    checkTokenValidity,
    refreshToken,
    ensureUserInfoLoaded
  }
}) 